package com.xuecheng.content.service.impl;

import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.util.Map;
@Component
public class PublishHtmlService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties prop;
    @Async
    public void publish(Map<String,Object> map,Long coursePubId) throws Exception {
        //睡眠20s，代表网络延迟
        Thread.sleep(20000);
        //一.页面静态化
        //1.构建configuration对象
        //2.指定字符集编码，指定模板位置
        //3.通过configuration获取对应的模板
        Template template = configuration.getTemplate("learing_article.ftl");
        //4.根据数据和模板，调用工具，获取静态页面的字符串
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //5.构造文件流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(html.getBytes());
        //二.存入MinIo
        //1.设置文件上传的位置及名字
        String path="/pages/"+coursePubId+".html";
        //2.构造文件上传对象
        PutObjectArgs putObjectArgs=PutObjectArgs.builder()
                .contentType("text/html")
                .stream(inputStream,inputStream.available(),-1)
                .object(path)
                .bucket(prop.getBucket())
                .build();
        //3.文件上传
        minioClient.putObject(putObjectArgs);
    }
}
